<script setup lang="js">
    import { ref, defineProps, watch, defineExpose, onMounted, onUnmounted } from "vue";
    import { ElMessage } from "element-plus";
    import { getPhoneCode, getLogin } from "../../api/login/index.js";
    import axios from 'axios';
    import { useRouter, useRoute } from 'vue-router'

    const route = useRoute()
    const currentPath = route.path
    const LoginShow = ref(localStorage.getItem("token") ? false : true)
    LoginShow.value = currentPath == '/' ? false : true
    const active = ref(0);
    const tabList = ref([{
        value: "手机号登录/注册",
        label: 0
        // }, {
        //     value: "注册账号",
        //     label: 1
    }])
    const page = ref({
        phone: "", code: ""
    })

    const isLoginClose = () => {
        LoginShow.value = !LoginShow.value;
    }

    const updateToken = (newToken) => {
        localStorage.setItem('token', newToken);
        triggerStorageEvent('token', newToken);
    };
    // 手动触发 localStorage 变化事件
    const triggerStorageEvent = (key, newValue) => {
        const event = new StorageEvent('storage', {
            key,
            newValue,
            oldValue: localStorage.getItem(key),
            storageArea: localStorage,
        });
        window.dispatchEvent(event);
    };

    const isLogin = ref(currentPath == '/' ? true : false);
    const countdownShow = ref(false);
    const countdown = ref(60);
    const isCounting = ref(false);
    let timer = null;
    const startCountdown = () => {
        if (isCounting.value || !isValidPhoneNumber(page.value.phone)) {
            ElMessage({
                message: "请输入正确的手机号",
                type: "error"
            })
            return;
        }
        isCounting.value = true;
        countdown.value = 60;
        getCode()
        timer = setInterval(() => {
            if (countdown.value > 0) {
                countdown.value--;
            } else {
                clearInterval(timer);
                isCounting.value = false;
            }
        }, 1000);
    };
    const clickLogin = async () => {
        if (page.value.code == "" || page.value.phone == "") {
            ElMessage({
                message: "请输入手机号和验证码",
                type: "error"
            })
            return
        }
        try {
            const res = await getLogin(page.value);
            if (res.code == 200) {
                LoginShow.value = false;
                localStorage.setItem("token", res.data.token)
                updateToken(res.data.token);
                return
            }
            ElMessage({ message: res.msg })
        } catch (error) {
            console.log(error);
        }

    }
    // 校验手机号的正则方法
    const isValidPhoneNumber = (phoneNumber) => {
        const phoneRegex = /^1(3[0-9]|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
        return phoneRegex.test(phoneNumber);
    }
    // 获取验证码
    const getCode = async () => {
        try {
            const res = await getPhoneCode({ phone: page.value.phone });
            if (res.code == 200) {
                ElMessage({
                    message: "发送成功！",
                    type: "success"
                })
                return
            }
            ElMessage({
                message: res.msg,
                type: "error"
            })
        } catch (error) {
            console.log(error);
        }
    }

    onMounted(() => {
        window.addEventListener('storage', handleStorageChange);
    });

    onUnmounted(() => {
        window.removeEventListener('storage', handleStorageChange);
    });

    const handleStorageChange = (event) => {
        if (event.key === 'token') {
            if (!event.newValue) {
                // token 被删除时调用的方法
                LoginShow.value = true; // 显示登录弹窗
                isLogin.value = currentPath == '/' ? true : false
                ElMessage.warning('登录状态已失效，请重新登录');
            }
        }
    };

    // 暴露方法给父组件
    defineExpose({
        isLoginClose
    });
</script>

<template>
    <div class="popup-content" v-if="LoginShow">
        <div class="popup-box">
            <Close class="close-icon" v-if="isLogin" @click="isLoginClose" />
            <div class="pupup-title">
                <div>请登录</div>
                <div class="df-aic">开启免费聊天
                    <img src="../../assets/image/icon/login-chat.png" style="width: 28px;height: 28px;margin-left: 6px">
                </div>
                <div class="tips">未注册的手机号将自动创建账号</div>
            </div>
            <div class="tab-list">
                <div v-for="item in tabList" :key="item.label" :class="active == item.label ? 'active' : ''"
                    @click="active = item.label">{{ item.value }}</div>
            </div>
            <div class="phone-content">
                <span>+86</span>
                <el-input v-model="page.phone" type="number" placeholder="请输入手机号" class="phone-input" maxlength="11"
                    style="width: calc(100% - 90px)" />
            </div>
            <div class="phone-content code-content">
                <el-input v-model="page.code" type="number" placeholder="请输入验证码" class="phone-input"
                    style="width: calc(100% - 160px)" />
                <div class="code-box">
                    <div class="code-btn" v-if="!isCounting" @click="startCountdown">发送验证码</div>
                    <div class="code-btn" v-else>{{ countdown }} 秒重试</div>
                </div>
            </div>
            <div class="tips-content">
                登录视为您已阅读并同意IVD<span>服务条款</span>和<span>隐私政策</span>
            </div>
            <div class="phone-content btn-content" @click="clickLogin">
                登录
            </div>
        </div>
    </div>
</template>

<style scoped lang="scss">
    .tips-content {
        width: 80%;
        margin: -10px auto 0;
        color: #999;
        font-size: 12px;
        span{
            color: #2D66B3;
            cursor: pointer;
            padding: 0 4px;
        }
    }

    .tips {
        color: #999;
        font-size: 12px;
        font-weight: 400;
        position: absolute;
    }

    :deep(.el-input__wrapper.is-focus) {
        box-shadow: none;
    }

    .close-icon {
        position: absolute;
        width: 24px;
        top: 8px;
        cursor: pointer;
        right: 8px;
    }

    :deep(.phone-input input::-webkit-inner-spin-button),
    :deep(.phone-input input::-webkit-outer-spin-button) {
        -webkit-appearance: none !important;
    }

    :deep(.phone-input input[type="number"]) {
        -moz-appearance: textfield;
    }

    :deep(.el-input__wrapper) {
        border: none;
        box-shadow: none;
    }


    .popup-content {
        position: fixed;
        width: 100%;
        height: 100vh;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 999;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, .3);

        .popup-box {
            width: 500px;
            border-radius: 20px;
            overflow: hidden;
            background-color: #fff;
            position: relative;

            .pupup-title {
                color: #000;
                padding: 20px 30px;
                font-size: 22px;
                font-weight: bold;
                overflow: hidden;
                background-size: contain;
                background-repeat: no-repeat;
                background-position: 0 0;
                background-image: url(../../assets/image/login-bgc.png);
            }

            .tab-list {
                margin: 20px 30px;
                display: flex;
                align-items: center;

                div {
                    padding: 4px 16px;
                    margin-right: 20px;
                    border-radius: 20px;
                    font-size: 14px;
                    color: #000;
                    cursor: pointer;

                }

                .active {
                    background-color: #2D66B3;
                    color: #fff;
                }
            }

            .phone-content {
                width: 80%;
                height: 50px;
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 20px auto;
                overflow: hidden;
                border-radius: 16px;
                border: 1px solid #D9D9D9;


                span {
                    width: 85px;
                    height: 50px;
                    display: flex;
                    padding-left: 15px;
                    align-items: center;
                    border-right: 1px solid #D9D9D9;
                }

                .phone-input {
                    height: 52px;
                    border: none;
                    margin-top: -1px;
                }
            }

            .code-box {
                width: 160px;
                height: 50px;
                border-radius: 16px;
                overflow: hidden;

                .code-btn {
                    width: 100%;
                    height: 100%;
                    color: #fff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: #2D66B3;
                    cursor: pointer;
                }
            }

            .btn-content {
                color: #fff;
                cursor: pointer;
                background-color: #2D66B3;
            }
        }
    }
</style>